import React, { useMemo, useState } from 'react'
import { Modal, Button } from 'antd'
import { createForm } from '@formily/core'
import { MonacoInput } from '@designable/react-settings-form'
import { Field, FormProvider } from '@formily/react'
import { MergedHelpers } from '@designable/event-system'

export interface IExpressionDialogSetterProps {
  value?: string
  onChange?: (value: string) => void
}

/**
 * 表达式对话框设置器组件
 * 用于编辑自定义表达式，支持 Monaco 编辑器
 */
export function ExpressionDialogSetter(props: IExpressionDialogSetterProps) {
  const [modalVisible, setModalVisible] = useState(false)

  const openModal = () => setModalVisible(true)
  const closeModal = () => setModalVisible(false)

  // 创建表单实例，处理表达式值的解析和初始化
  const form = useMemo(() => {
    const strip = String(props.value || '')
      .replace(/^\s*\{\{\s*/, '')
      .replace(/\s*\}\}\s*$/, '')

    return createForm({
      values: {
        customExpression: strip,
      },
    })
  }, [modalVisible, props.value])

  // 处理表单提交
  const handleSubmit = () => {
    form.submit((values) => {
      const raw = values.customExpression
      const isEmpty = !raw || String(raw).trim() === ''
      props.onChange?.(isEmpty ? '' : `{{${raw}}}`)
    })
    closeModal()
  }

  return (
    <>
      <Button block onClick={openModal}>
        自定义表达式
      </Button>
      <Modal
        title="自定义表达式"
        width="70%"
        centered
        bodyStyle={{ padding: 10 }}
        transitionName=""
        maskTransitionName=""
        open={modalVisible}
        onCancel={closeModal}
        destroyOnClose
        onOk={handleSubmit}
      >
        <FormProvider form={form}>
          <Field
            name="customExpression"
            component={[
              MonacoInput,
              {
                width: '100%',
                height: 400,
                language: 'typescript',
                helpCode: MergedHelpers,
                options: {
                  minimap: {
                    enabled: false,
                  },
                },
              },
            ]}
          />
        </FormProvider>
      </Modal>
    </>
  )
}
